package demo.retry;

import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.WaitStrategy;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * 
 *
 * @author haijun
 * @version 1.0.0
 * @email "mailto:iamxiaohaijun@gmail.com"
 * @date 2023.07.19 19:14
 * @since 2023.1.1
 */
public class ProgressiveWaitStrategy implements WaitStrategy {

    /**
     * Times
     */
    private final Long[] times;

    /**
     * Progressive wait strategy
     *
     * @param times    times
     * @param timeUnit time unit
     * @since 2023.1.1
     */
    public ProgressiveWaitStrategy(Long[] times, TimeUnit timeUnit) {
        Assert.notEmpty(times);
        final Long[] ftime = new Long[times.length];
        Stream.iterate(0, n -> n + 1).limit(times.length).forEach(v -> {
            ftime[v] = timeUnit.toMillis(times[v]);
        });
        this.times = ftime;
    }

    /**
     * Compute sleep time
     *
     * @param attempt attempt
     * @return the long
     * @since 2023.1.1
     */
    @Override
    public long computeSleepTime(Attempt attempt) {
        //获取到当前执行的次数
        long attemptNumber = attempt.getAttemptNumber() - 1;
        Assert.isTrue(attemptNumber < this.times.length, "");
        return times[(int) attemptNumber];
    }
}
